<template>
  <el-dialog
    title="灯控状态"
    v-model="state.show"
    width="1000px"
    :close-on-press-escape="false"
    :close-on-click-modal="false"
    append-to-body
    destroy-on-close
  >
    <el-button type="primary" icon="Refresh" @click="restartAll" style="margin-bottom: 10px;">批量重启</el-button>

    <el-table :data="state.statusList">
      <el-table-column label="序号" type="index" align="center" width="50" />
      <el-table-column label="设备自定义名称" prop="deviceCustomName">
        <template #default="scope">
          {{ scope.row.deviceCustomName || '未定义' }}
        </template>
      </el-table-column>
      <el-table-column label="产品" prop="productKey" width="180">
        <template #default="scope">
          {{ getProductName(scope.row.productKey) }}
        </template>
      </el-table-column>
      <el-table-column label="设备DN" prop="deviceName" />
      <el-table-column label="状态" prop="online" align="center" width="80">
        <template #default="scope">
          <el-tag v-if="scope.row.online" type="success" size="small">在线</el-tag>
          <el-tag v-else type="danger" size="small">离线</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="开关" prop="sw" align="center" width="80">
        <template #default="scope">
          <el-switch v-model="scope.row.sw" :active-value = "1" :inactive-value = "0" @click="switchChange(scope.row)" />
        </template>
      </el-table-column>
      <el-table-column label="调光" prop="sl" align="center" width="260">
        <template #default="scope">
          <el-slider v-model="scope.row.sl" :max="100" :min="0" @change="percentageChange(scope.row)" />
        </template>
      </el-table-column>
    </el-table>
  </el-dialog>
</template>

<script lang="ts" setup>
import { getProductsList, IProductsVO } from '../api/products.api'
import { propertySet, devicePropertyLogs } from '../api/devices.api'
// 引入公共方法获取设备属性、判断设备
import { getDeviceProperties, isLightController } from '@/utils/deviceUtils'

const state = reactive({
  show: false,
  row: {} as any,
  sw: 0,
  sl: 0,
  historyTime: [new Date(new Date().getTime() - 24 * 3600 * 1000), new Date(new Date().getTime() + 24 * 3600 * 1000)],
  swName: '',
  slName: '',
  gwmac: '', // 微自然
  statusList: [],
  loading: false
})

const restartAll = async () => {
  if (state.statusList.length === 0) {
    ElMessage.warning('没有可重启的设备')
    return
  }
  const confirmResult = await ElMessageBox.confirm('确认要批量重启当前页面所有设备吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    if (confirmResult === 'confirm') {
    state.loading = true
    // 遍历所有设备并调用重启接口
    await Promise.allSettled(
      state.statusList.map(device => restart(device))
    )
    ElMessage.success('批量重启命令已下发')
  }
}

const restart = async (device: any) => {
  propertySet({
    deviceId: device.deviceId,
    args: { cmd_type: '0' }
  })
}

const openDialog = (list: any) => {
  state.show = true

  const filteredList = list.filter(item => isLightController(item.product.productKey))

  state.statusList = filteredList.map(item => {
    const { swName, slName, gwmac } = getDeviceProperties(item.product.productKey)
    // 单独处理微自然单灯控制器的gwmac
    const deviceGwmac = item.product.productKey === 'hATm2Tswh3TDik8W' ? item.parentId : gwmac
    return {
      ...item,
      swName,
      slName,
      gwmac: deviceGwmac,
      sw: 0, // 默认开关状态
      sl: 0  // 默认亮度值
    }
  })
  nextTick(() => {
    // 查询所有设备的历史数据
    queryAllDevicesHistory()
  })
}

// 批量查询历史数据的方法
const queryAllDevicesHistory = async () => {
  try {
    // 使用Promise.all同时查询所有设备的历史数据
    await Promise.all(state.statusList.map(async (device) => {
      await queryDeviceHistory(device)
    }))
    console.log('所有设备历史数据查询完成')
  } catch (error) {
    ElMessage.error('历史数据查询失败')
    console.error('历史数据查询错误:', error)
  }
}

// 单个设备历史数据查询方法
const queryDeviceHistory = async (device: any) => {
  const end = state.historyTime[1]
  const start = state.historyTime[0]

  // 查询开关历史
  const swResult = await devicePropertyLogs({
    deviceId: device.deviceId,
    name: device.swName,
    start: start.getTime(),
    end: end.getTime()
  })

  // 查询调光历史
  const slResult = await devicePropertyLogs({
    deviceId: device.deviceId,
    name: device.slName,
    start: start.getTime(),
    end: end.getTime()
  })

  // 更新设备状态数据
  if (swResult.data && swResult.data.length > 0) {
    device.sw = Number(swResult.data[0].value)
  }
  if (slResult.data && slResult.data.length > 0) {
    device.sl = Number(slResult.data[0].value)
  }
}

// 开关按钮
const switchChange = async (device: any) => {
  const args: Record<string, any> = {}
  args[device.swName] = device.sw
  if (device.gwmac) {
    args.gwmac = device.gwmac
  }
  propertySet({
    deviceId: device.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('开关成功')
    } else {
      ElMessage.error(res.message)
      // 回滚状态
      device.sw = device.sw === 1 ? 0 : 1
    }
  })
}

// 调光按钮
const percentageChange = async (device: any) => {
  const args: Record<string, any> = {}
  args[device.slName] = device.sl
  if (device.gwmac) {
    args.gwmac = device.gwmac
  }
  propertySet({
    deviceId: device.deviceId,
    args: args,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success('调光成功')
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 产品字典
const productOptions = ref<IProductsVO[]>([])
// 获取产品下拉框数据
const getProductList = () => {
  getProductsList({
    pageNum: 1,
    pageSize: 99999,
  }).then((res) => {
    productOptions.value = res.data.rows || []
  })
}
getProductList()
// 获取产品名称
const getProductName = (productKey) => {
  const product = productOptions.value.find(p => p.productKey === productKey)
  return product ? product.name : ''
}

defineExpose({
  openDialog,
})
</script>